from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.users.models import User
from django.http import JsonResponse
import re




class UsernameCountView(View):
    def get(self,request,username):
        # if not re.match('[a-zA-Z0-9_-]{5,20}',username):
        #     return JsonResponse({'code':200,'errmsg':'username is not satisfy a need'})
        count = User.objects.filter(username=username).count()
        return  JsonResponse({'code':0,'count':count,'errmsg':'ok'})

class MobileCountView(View):
    def get(self,request,mobile):
        count =User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code':0,'count':count,'errmsg':'ok'})


import json
class RegisterView(View):
    def post(self,request):
        body_bytes=request.body
        body_str=body_bytes.decode()
        body_dict=json.loads(body_str)
        username=body_dict.get('username')
        password = body_dict.get('password')
        password2 = body_dict.get('password2')
        mobile = body_dict.get('mobile')
        allow = body_dict.get('allow')

        if not all([username,password,password2,mobile,allow]):
            return JsonResponse({'code':400,'errmsg':'have err'})

        if not re.match(r'^[a-zA-Z0-9_]{5,20}$',username):
            return JsonResponse({'code': 400, 'errmsg': 'have username err'})

        if not User.objects.filter(username=username).count()==0:
            return JsonResponse({'code': 400, 'errmsg': 'have the same username'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$',password):
            return JsonResponse({'code':400,'errmsg':'password have err'})

        if password != password2:
            return JsonResponse({'code':400,'errmsg':'the two password have not the same'})

        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return JsonResponse({'code':400,'errmsg':'mobile err'})

        if not User.objects.filter(mobile=mobile).count()==0:
            return JsonResponse({'code':400,'errmsg':'have the same mobile'})

        if allow !=True:
            return JsonResponse({'code':400,'errmsg':'allow have err'})

        use=User.objects.create_user(username=username,password=password,mobile=mobile)
        from django.contrib.auth import login
        login(request,use)
        return JsonResponse({'code': 0,'errmsg':'ok' })

class LoginView(View):
    def post(self,request):
        data=json.loads(request.body.decode())
        username=data.get('username')
        password = data.get('password')
        remembered = data.get('remembered')
        if not all([username,password]):
            return JsonResponse({'code':400,'errmsg':'参数不全'})
        if re.match('1[3-9]\d{9}',username):
            User.USERNAME_FIELD='mobile'
        else:
            User.USERNAME_FIELD = 'username'
        from django.contrib.auth import authenticate,login
        #通过authenticate传递username，password，如果正确返回user信息，否则返回None
        user=authenticate(username=username,password=password)
        if user is None:
            return JsonResponse({'code':400,'errmsg':'用户名或密码不正确'})
        login(request,user)



        if remembered :
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)
        response= JsonResponse({'code':0,'errmsg':'ok'})
        response.set_cookie('username',username)
        # 登录后合并
        from apps.carts.utils import merge_cookie_to_redis
        response=merge_cookie_to_redis(request,response)
        return response

from django.contrib.auth import logout
class LogoutView(View):
    def delete(self,request):
        logout(request)
        response= JsonResponse({'code':0,'errmsg':'ok'})
        response.delete_cookie('username')
        return response

from utils.views import LoginRequiredJSONMixin
class CenterView(LoginRequiredJSONMixin,View):
    def get(self,request):
        #request.user 就是 已经登录的用户信息，是来源于中间件
        info_data={
            'username':request.user.username,
            'email':request.user.email,
            'mobile':request.user.mobile,
            'email_active':request.user.email_active,

        }
        return JsonResponse({'code':'0','errmsg':'ok','info_data':info_data})

class EmailView(LoginRequiredJSONMixin,View):
    def put(self,request):
        """
         1. 接收请求
        2. 获取数据
        3. 保存邮箱地址
        4. 发送一封激活邮件
        5. 返回响应

        """
        data=json.loads(request.body.decode())
        email=data.get('email')
        user=request.user
        user.email=email
        user.save()
        from django.core.mail import send_mail
        #subject, message, from_email, recipient_list
        subject='美多商城激活邮件'
        message=''
        from_email='美多商城<xinqinlaodong22@163.com>'
        recipient_list=['1137766487@qq.com']
        from apps.users.utils import generic_email_verify_token
        token = generic_email_verify_token(request.user.id)
        verify_url='http://www.meiduo.site:8080/success_verify_email.html?token=%s'%token
        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)

        # html_message='点击激活 <a href="http://www.baidu.com/?token=%s">激活</a>'%token
        # send_mail(subject=subject,
        #           message=message,
        #           from_email=from_email,
        #           recipient_list=recipient_list,
        #           html_message=html_message)
        from celery_tasks.email.tasks import celery_send_email
        celery_send_email.delay(
            subject=subject,
            message=message,
            from_email=from_email,
            recipient_list=recipient_list,
            html_message=html_message)
        return JsonResponse({'code':0,'errmsg':'ok'})


class EmailVerifyView(View):
    def put(self,request):
        token=request.GET.get('token')
        if token is None:
            return JsonResponse({'code':400,'errmsg':'参数有误'})
        from apps.users.utils import check_verify_token
        user_id=check_verify_token(token)
        if user_id is None:
            return JsonResponse({'code': 400, 'errmsg': '参数有误'})
        user=User.objects.get(id=user_id)
        user.email_active=True
        user.save()
        return JsonResponse({'code':0,'errmsg':'ok'})

from apps.users.models import Address
class AddressCreateView(LoginRequiredJSONMixin,View):
    def post(self,request):
        data=json.loads(request.body.decode())
        # 2.获取参数，验证参数
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')
        user=request.user
        # 验证参数 （省略）
        # 2.1 验证必传参数
        # 2.2 省市区的id 是否正确
        # 2.3 详细地址的长度
        # 2.4 手机号
        # 2.5 固定电话
        # 2.6 邮箱
        # if not all([receiver, province_id, city_id, district_id, place, mobile]):
        #     return http.JsonResponse({'code': 400,
        #                               'errmsg': '缺少必传参数'})
        #
        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return http.JsonResponse({'code': 400,
        #                               'errmsg': '参数mobile有误'})
        #
        # if tel:
        #     if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
        #         return http.JsonResponse({'code': 400,
        #                                   'errmsg': '参数tel有误'})
        # if email:
        #     if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
        #         return http.JsonResponse({'code': 400,
        #                                   'errmsg': '参数email有误'})

        address=Address.objects.create(
            user=user,
            title=receiver,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email )
        address_dict = {
            'id': address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return JsonResponse({'code':0,'reemsg':'ok','address':address_dict})

class AddressView(LoginRequiredJSONMixin,View):
    def get(self,request):
        user = request.user
        # addresses=user.addresses

        addresses = Address.objects.filter(user=user, is_deleted=False)
        # 2.将对象数据转换为字典数据
        address_list = []
        for address in addresses:
            address_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })
        # 3.返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'addresses': address_list})

from apps.goods.models import SKU
from django_redis import get_redis_connection
class UserHistoryView(LoginRequiredJSONMixin,View):
    def post(self,request):
        user=request.user
        data=json.loads(request.body.decode())
        sku_id=data.get('sku_id')
        try:
            sku=SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'have no this goods'})
        redis_cli=get_redis_connection('history')
        redis_cli.lrem('history_%s'%user.id,0,sku_id)
        redis_cli.lpush('history_%s'%user.id,sku_id)
        redis_cli.ltrim('history_%s'%user.id,0,4)
        return JsonResponse({'code':0,'errmsg':'ok'})
    def get(self,request):
        redis_cli=get_redis_connection('history')
        ids=redis_cli.lrange('history_%s'%request.user.id,0,4)
        history_list=[]
        for sku_id in ids:
            sku=SKU.objects.get(id=sku_id)
            history_list.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })
        return JsonResponse({'code':0,'errmsg':'ok','skus':history_list})